package edu.neu.cs6515.gui;

import java.awt.Component;
import java.awt.FlowLayout;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.ListSelectionModel;

import lombok.Getter;

import edu.neu.cs6515.xml.Tile;

/**
 * to render tiles in hand
 */
public class TilesInHandRenderer extends JPanel {

    @Getter
    private JList<Tile> tilesMenu;

    private static final long serialVersionUID = 1L;

    private static final int GAP_BTWEEN_TILES_IN_RENDERER = 10;

    /**
     * C'tor
     * 
     */
    public TilesInHandRenderer() {
        super();
        this.tilesMenu = new JList<Tile>();
		this.tilesMenu.setLayoutOrientation(JList.HORIZONTAL_WRAP);
		this.tilesMenu.setVisibleRowCount(1);
        this.tilesMenu.setCellRenderer(new TilesMenuItemRenderer());
		JScrollPane jsp = new JScrollPane(this.tilesMenu);
		this.add(jsp);

        this.setBorder(BorderFactory.createTitledBorder("Tiles In Hand"));
        this.setLayout(new FlowLayout(FlowLayout.LEADING,
                GAP_BTWEEN_TILES_IN_RENDERER, 0));
    }

	public int getSelectedIndex() {
		return this.tilesMenu.getSelectedIndex();
	}

    /**
     * class to render items of the tiles in hand drop down menu
     */
    private class TilesMenuItemRenderer implements ListCellRenderer<Object> {
        @Override
        public Component getListCellRendererComponent(final JList<?> list,
                final Object obj, final int index, final boolean arg3,
                final boolean arg4) {
            if (obj != null) {
                TileRenderer tileRenderer = new TileRenderer((Tile) obj, arg3);
                return tileRenderer;
            }
            return new JLabel();
        }
    }

	public void initializeTilesInHandRenderer(final List<Tile> tiles){
		final DefaultListModel<Tile> dlm = new DefaultListModel<Tile>();
		for (Tile t : tiles) {
			dlm.addElement(t);
		}
		tilesMenu.setModel(dlm);
		tilesMenu.setSelectionMode(
				ListSelectionModel.SINGLE_SELECTION);
		tilesMenu.setSelectedIndex(0);
	}

    /**
     * 
     * @param tiles
     *            tiles to be rendered
     */
    public void update(final List<Tile> tiles) {
        initializeTilesInHandRenderer(tiles);
    }
}
